import { _decorator, Button, Component, director, Node, Prefab, sys } from 'cc';
import { EffecLayer } from './EffecLayer';
import GameModel from './GameModel';
import { GridView } from './GridView';
import { AudioMgr } from './AudioMgr';
import { TimerScript } from './TimerScript';
import { GameOverController } from './GameOverController';
import { LocalStorageKey } from './ConstValue';
import { Toast } from './Toast';
const { ccclass, property } = _decorator;

@ccclass('GameMainController')
export class GameMainController extends Component {

    @property(Node)
    private grid: Node = null

    @property(Button)
    private exChangePosition: Button = null // 打乱位置按钮

    @property(Button)
    private lowCleanBtn: Button = null // 垂直消失

    @property(Button)
    private rowCleanBtn: Button = null // 横向消失


    @property(Button)
    private backBtn: Button = null  // 返回按钮
    @property(TimerScript)
    private timer: TimerScript = null // 定时器

    @property(Node)
    private gameOverNode: Node = null  // 游戏结束画面

    private gameModel: GameModel
    private gridScript: GridView

    start() {
        AudioMgr.inst.play("musics/gamescenebgm", 1, true)
        this.gameModel = new GameModel()
        this.gameModel.init(5);
        this.gridScript = this.grid.getComponent(GridView);
        this.gridScript.setController(this);
        this.gridScript.initWithCellModels(this.gameModel.getCells());
        this.exChangePosition.node.on(Button.EventType.CLICK, this.exchangePositionClick, this);
        this.lowCleanBtn.node.on(Button.EventType.CLICK, () => {
            this.cleanLineClick(1)
        }, this);
        this.rowCleanBtn.node.on(Button.EventType.CLICK, () => {
            this.cleanLineClick(2)
        }, this);
        this.backBtn.node.on(Button.EventType.CLICK, this.back, this);
        this.timer.startCountdown()
        this.timer.setController(this)
    }

    update(deltaTime: number) {

    }

    public selectCell(pos) {
        return this.gameModel.selectCell(pos);
    }

    // type 1 垂直 2 横向
    private cleanLineClick(type: number) {    
        if (this.subtractionGold(3)) {
            if (type == 1) {
                this.gridScript.colClean(this.gameModel.colCrush())
            } else if (type == 2) {
                this.gridScript.colClean(this.gameModel.rowCrush())
            }
        } else {
            Toast.inst.showToast("Insufficient gold coins")
        }
    }

    private exchangePositionClick() {
        if (this.subtractionGold(5)) {
            if (this.gameModel) {
                AudioMgr.inst.playOneShot("musics/click.bubble")
                this.gameModel.cleanCells()
                this.gameModel.init(5);
                var gridScript: GridView = this.grid.getComponent(GridView);
                gridScript.setController(this);
                gridScript.initWithCellModels(this.gameModel.getCells());

            }
        } else {
            Toast.inst.showToast("Insufficient gold coins")
        }
    }

    private restartGameChangePosition() {
        if (this.gameModel) {
            AudioMgr.inst.playOneShot("musics/click.bubble")
            this.gameModel.cleanCells()
            this.gameModel.init(5);
            var gridScript: GridView = this.grid.getComponent(GridView);
            gridScript.setController(this);
            gridScript.initWithCellModels(this.gameModel.getCells());
        }
    }

    public cleanCmd() {
        this.gameModel.cleanCmd();
    }

    public back() {
        this.updataGoldAndScore()
        AudioMgr.inst.playOneShot("musics/click.bubble")
        window.globalParam = {
            sceneName: "HomeScene"
        };
        director.loadScene("LoadingScene")
    }

    public updataGoldAndScore() {
        let gridScore = this.gridScript.getCurScore();
        let gridGold = this.gridScript.getCurGold();
        let score = sys.localStorage.getItem(LocalStorageKey.SCORE)
        if (score == null) {
            sys.localStorage.setItem(LocalStorageKey.SCORE, gridScore + "")
        } else if (score && gridScore > Number(score)) {
            sys.localStorage.setItem(LocalStorageKey.SCORE, gridScore + "")
        }
        let goldNum = sys.localStorage.getItem(LocalStorageKey.GOLD)
        if (goldNum) {
            let sumGoldNum: number = Number(goldNum) + Number(gridGold)
            sys.localStorage.setItem(LocalStorageKey.GOLD, sumGoldNum + "")
        } else {
            sys.localStorage.setItem(LocalStorageKey.GOLD, gridGold + "")
        }
    }

    public gameOver() {
        window.globalParam = {
            score: this.gridScript.getCurScore() + "",
            gold: this.gridScript.getCurGold() + ""
        };
        this.timer.stopCountdown()
        this.gameOverNode.getComponent(GameOverController).setController(this)
        this.gameOverNode.active = true
    }

    public restartGame() {
        this.timer.startCountdown()
        this.gameOverNode.active = false
        this.gridScript.setCurScore(0)
        this.gridScript.setCurGold(0)
        this.gridScript.refreshGold()
        this.gridScript.refreshScore() 
        this.restartGameChangePosition();
    }

    public adjustTimer(time) {
        if (this.timer) {
            this.timer.adjustTime(time)
        }
    }

    public subtractionGold(goldNum: number): boolean {
        let goldCurSumNum = this.gridScript.getCurGold() // 获取这局赚的金币
        let historyGold = sys.localStorage.getItem(LocalStorageKey.GOLD)
        if (!historyGold) {
            historyGold = 0;
        }
        let goldSum = Number(historyGold) + Number(goldCurSumNum)
        if (goldSum < goldNum) {
            return false
        }
        let syGoldSum = Number(goldCurSumNum) - Number(goldNum)
        if (syGoldSum < 0) {
            this.gridScript.setCurGold(0)
            historyGold = Number(historyGold) + Number(syGoldSum)
            sys.localStorage.setItem(LocalStorageKey.GOLD, historyGold)
        } else {
            this.gridScript.setCurGold(syGoldSum)
        }
        this.gridScript.refreshGold()
        this.gridScript.refreshShowGold()
        return true
    }
}

